package com.ccb.sc.message.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ccb.sc.message.convert.MessageConvert;
import com.ccb.sc.message.vo.MessageVo;
import com.ccb.sc.common.bind.page.PageParams;
import com.ccb.sc.common.bind.page.PageVo;
import com.ccb.sc.common.modules.message.entity.Message;
import com.ccb.sc.common.modules.message.enums.MessageStatus;
import com.ccb.sc.common.modules.message.mapper.MessageMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 会员消息表 服务实现类
 * </p>
 *
 * @author ken
 * @since 2022-08-14
 */
@Service
public class AppMessageService extends ServiceImpl<MessageMapper, Message> {

    public int countUnRead(Long memberId) {
        return (int) this.count(Wrappers.<Message>lambdaQuery().eq(Message::getMemberId, memberId).eq(Message::getStatus, MessageStatus.UN_READ));
    }

    public PageVo<MessageVo> selectMessages(Long memberId, PageParams queryParam) {
        Page<Message> page = new Page<>(queryParam.getCurrent(), queryParam.getPageSize());
        Page<Message> messagePage = this.page(page, Wrappers.<Message>lambdaQuery().eq(Message::getMemberId, memberId).orderByDesc(Message::getId));
        List<Message> list = messagePage.getRecords();
        if (CollectionUtils.isEmpty(list)) {
            return PageVo.create(queryParam.getCurrent(), queryParam.getPageSize(), 0, Lists.newArrayList());
        }
        List<MessageVo> result = MessageConvert.INSTANCE.entity2ListVo(list);
        // 更新未读消息记录
        List<Message> unReadList = list.stream().filter(message -> message.getStatus().equals(MessageStatus.UN_READ)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(unReadList)) {
            for (Message message : unReadList) {
                message.setStatus(MessageStatus.READ);
            }
            this.updateBatchById(unReadList);
        }
        return PageVo.create(queryParam.getCurrent(), queryParam.getPageSize(), messagePage.getTotal(), result);
    }

}
